package com.wlr.blog.article.service.impl;

import com.wlr.blog.util.common.strategy.SearchStrategy;
import com.wlr.blog.web.common.entity.Article;
import com.wlr.blog.web.common.mapper.ArticleMapper;
import com.wlr.blog.web.common.vo.ArticleSearchVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lrwang
 * @version 1.0
 * @date 2022/11/14 22:41
 */
@Service("mysqlServiceImpl")
public class MysqlArticleSearch extends SearchStrategy<ArticleSearchVO> {
    @Autowired
    ArticleMapper articleMapper;
    /**
     * 高亮标签
     */
    public static final String PRE_TAG = "<span style='color:#f47466'>";
    /**
     * 高亮标签
     */
    public static final String POST_TAG = "</span>";

    /**
     * Mysql搜索方法
     *
     * @param keywords 关键字
     * @return 搜索到的列表
     */
    @Override
    public List<ArticleSearchVO> search(String keywords) {
        List<Article> articles = articleMapper.selectFulltext(keywords);
        // 高亮处理
        return articles.stream().map(item -> {
            // 获取关键词第一次出现的位置
            String articleContent = item.getArticleContent();
            int index = item.getArticleContent().indexOf(keywords);
            if (index != -1) {
                // 获取关键词前面的文字
                int preIndex = index > 25 ? index - 25 : 0;
                String preText = item.getArticleContent().substring(preIndex, index);
                // 获取关键词到后面的文字
                int last = index + keywords.length();
                int postLength = item.getArticleContent().length() - last;
                int postIndex = postLength > 175 ? last + 175 : last + postLength;
                String postText = item.getArticleContent().substring(index, postIndex);
                // 文章内容高亮
                articleContent = (preText + postText).replaceAll(keywords, PRE_TAG + keywords + POST_TAG);
            }
            // 文章标题高亮
            String articleTitle = item.getArticleTitle().replaceAll(keywords, PRE_TAG + keywords + POST_TAG);
            return ArticleSearchVO.builder()
                    .id(item.getId())
                    .articleTitle(articleTitle)
                    .articleContent(articleContent)
                    .build();
        }).collect(Collectors.toList());
    }
}
